package com.example.gobang.game;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Description: 房间管理器的类，我们希望这个类只有唯一实例，所以将其交给 Spring 管理
 * Date: 2024-09-05
 * Time: 22:17
 */
@Component
public class RoomManager {
    ConcurrentHashMap<String,Room> rooms = new ConcurrentHashMap<>();
    ConcurrentHashMap<Integer,String> userId2RoomId = new ConcurrentHashMap<>();

    public void add(Room room,Integer userId1,Integer userId2) {
        rooms.put(room.getRoomId(),room);
        userId2RoomId.put(userId1,room.getRoomId());
        userId2RoomId.put(userId2,room.getRoomId());
    }

    public void remove(String roomId,Integer userId1,Integer userId2) {
        rooms.remove(roomId);
        userId2RoomId.remove(userId1);
        userId2RoomId.remove(userId2);
    }

    public Room getRoomByRoomId(String roomId) {
        return rooms.getOrDefault(roomId,null);
    }

    /**
     // 根据用户 ID 找到他所在的房间
     * @param userId
     * @return
     */
    public Room getRoomByUserId(Integer userId) {
        String roomId = userId2RoomId.getOrDefault(userId,null);
        if (roomId == null) {
            // userId -> roomId 映射关系不存在，直接返回 null
            return null;
        }
        return rooms.get(roomId);
    }
}
